/**
 * Package name:indi.yangshenhui.common
 * File name:Main.java
 * Date:2016年8月31日-下午2:10:48
 * feiniu.com Inc.Copyright (c) 2013-2015 All Rights Reserved.
 *
 */
package indi.yangshenhui.common.grpc;

import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import indi.yangshenhui.common.grpc.service.HelloWorldImpl;
import io.grpc.Server;
import io.grpc.ServerBuilder;

/**
 * @ClassName Main
 * @Description GRPC服务主函数
 * @date 2016年8月31日 下午2:10:48
 * @author shenhui.yang
 * @version 1.0.0
 *
 */
public class Main {
	private static final Logger log = LoggerFactory.getLogger(Main.class);

	private int port = 50051;
	private Server server;

	private void start() throws IOException {
		server = ServerBuilder.forPort(port).addService(new HelloWorldImpl()).build().start();
		log.info("*** server started, listening on " + port);
		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				log.info("*** shutting down grpc server since JVM is shutting down");
				Main.this.stop();
				log.info("*** server shut down");
			}
		});
	}

	private void stop() {
		if (server != null) {
			server.shutdown();
		}
	}

	private void blockUntilShutdown() throws InterruptedException {
		if (server != null) {
			server.awaitTermination();
		}
	}

	public static void main(String[] args) throws IOException, InterruptedException {
		final Main server = new Main();
		server.start();
		server.blockUntilShutdown();
	}

}
